import java.util.Arrays;

/**
 * @Author 12629
 * @Description：
 */
public class HashBuck {

    public static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;

    public static final float LOAD_FACTOR = 0.75f;

    public void put(int key,int val) {
        //1. 通过哈希函数 找到位置
        int index = key % array.length;
        //2.判断当前数组下标的链表 有没有Key相同的，如果有 更新val
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //3. 如果没有 进行尾插法(JDK8开始是尾插法，这之前是头插法) 我写头插法

        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;

        usedSize++;

        //4. 计算一下当前的负载因子 如果超过了0.75 那么就需要扩容
        if(doLoadFactor() >= LOAD_FACTOR) {
            //扩容
            //array = Arrays.copyOf(array,array.length*2); error
            resize();
        }

    }

    private void resize() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private float doLoadFactor() {
        return usedSize*1.0f / array.length;
    }


    public int get(int key) {
        //1. 通过哈希函数 找到位置
        int index = key % array.length;
        //2.判断当前数组下标的链表 有没有Key相同的，如果有 更新val
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
